package com.sx.micowell.framework.adapter.binding.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.viewpager.widget.PagerAdapter;

import java.util.List;

public abstract class BasePagerAdapter<T, B extends ViewDataBinding> extends PagerAdapter {
    private final int layoutId;
    private List<T> mData;

    public void setmData(List<T> mData) {
        this.mData = mData;
    }

    public BasePagerAdapter(int layoutId) {
        this.layoutId = layoutId;
    }

    @Override
    public int getCount() {
        return mData==null?0:mData.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
          return view == object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        View view = LayoutInflater.from(container.getContext()).inflate(layoutId, container, false);
        bind(DataBindingUtil.bind(view),mData.get(position));
        container.addView(view);
        return view;
    }

    abstract void bind(B bind,T data);

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }
}
